

import { App } from './app';
import './dx-ext';
import './manager';
import './basics';
import './diction';
import './domp';

window.page_watch_data = {
	hash:'',
	click:false,
	skip:0
};
jQuery.extend({
	crudStoreResp: null,

	crudStore: function(url, options) {
		var SERVICE_URL = url;
		options = $.extend({
			onDataArrived: function(data) {
				return data;
			}
		}, options);

		return new DevExpress.data.CustomStore($.extend({}, options, {
			load: function(loadOptions) {
				var u = new Url(SERVICE_URL);
				if(window.page_watch_data.skip&&window.page_watch_data.click&&window.page_watch_data.hash==location.hash){
					loadOptions.skip = window.page_watch_data.skip;
					$('.crud-grid').dxDataGrid('instance').pageIndex((loadOptions.skip/10))
					window.page_watch_data = false;
					return 
				};
				window.page_watch_data = {
					skip:loadOptions.skip,
					click:true,
					hash:location.hash
				}
				u.query._param = JSON.stringify(loadOptions);
				return $.getJSON(u).then(function(resp, status, xhr) {
					// var totalCount = xhr.getResponseHeader('X-Total-Count');
					if(resp.errcode === 200){
						resp = {
						status: 'success',
						totalCount: resp.totalCount,
						data:resp.data
						};
						return options.onDataArrived(resp);
					}else{
						new DevExpress.ui.notify({message:'服务错误，请联系管理员'},'warning',1500)
					}	
					
				});
			},

			byKey: function(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);
				return $.getJSON(u).then(function (resp) {
					return resp.data;
				});
			},

			insert: function(values) {
				return $.ajax({
					type:"post",
					url:SERVICE_URL,
					data:JSON.stringify(values),
					contentType:"application/json",
					dataType:'json'
				}).always(function(resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			update: function(key, values) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "PUT",
					data: JSON.stringify(values),
					contentType:"application/json",
					dataType:'json'
				}).always(function(resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			remove: function(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "DELETE"
				});
			}

		}));
	},

	crud: function(options) {
		if(typeof(options) === 'object') {
			var app = options.app,
				route = options.route,
				store = jQuery.crudStore(options.url || API(route), options.store);


			options.search = $.extend({
				mobile: 'mobile',
				name: 'uname',
				dateA: 'dateA'
			}, options.search);

			// list

			app.get('#/' + route, function() {
				var eventContext = this,
					capable = $.extend({
						create: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-list").html(), $.extend({}, options, {
					capable: capable
				}))).dxInit();

				var gridType = options.gridType || "dxDataGrid";
				if(options.buttons) {
					$.each(options.buttons, function(i, button) {
						button.instance = $("<div>").dxButton($.extend({
							type: 'normal',
							onClick: function(e) {
								var selections = [];

								if(options.onGetSelectedRowsData) {
									selections = options.onGetSelectedRowsData.call(eventContext, $("#content .crud-grid"));
								} else if(!options.onRenderGrid) {
									selections = $("#content .crud-grid")[gridType]('getSelectedRowsData');
								}

								button.onRoute && button.onRoute.call(eventContext, e.component, selections);
							}
						}, button)).appendTo(
							$("#content .crud-buttons")).dxButton('instance');
					});
				}

				var defaultToolbarItems = [];
				if (options.capable.create) {
					defaultToolbarItems.push('create');
				}

				var toolbarOptions = options.toolbar ? options.toolbar : {
					items: defaultToolbarItems
				};

				$.each(toolbarOptions.items, function(i, item) {
					if (item === 'create') {
						toolbarOptions.items[i] = {
							location: 'before',
							widget: 'dxButton',
							options: {
								text: '新建',
								onClick: function() {
									eventContext.redirect('#/' + route + '/edit');
								}
							}
						};
					}
				});

				$("#content .toolbar").dxToolbar(toolbarOptions);

				var ds = new DevExpress.data.DataSource({
					store: store
				});

				if(eventContext.params) {
					$.each(eventContext.params, function(k, v) {
						if(typeof(v) !== 'function' && typeof(v) !== 'object') {
							ds.filter(k, '=', v);
						}
					});
				}


				var param = {
					dataSource: ds,
					allowColumnResizing: true,
					selection: {
						mode: "multiple",
						showCheckBoxesMode: 'always',
						selectAllMode: 'page'
					},
					remoteOperations: true,
					paging: {
						pageSize: 10,
						pageIndex: 0
					},
					onSelectionChanged: function(e) {
							if(options.buttons){
							$.each(options.buttons, function(i, button) {
								button.onSelectionChanged &&
									button.onSelectionChanged.call(eventContext, button.instance, e.selectedRowsData, e.component);
							});
						}
					},
					onContentReady:function(){
						$('.dx-page').on('click',function(e){
							window.page_watch_data.click = false;
						})
					}
				};

				if(options.columns) {
					for(var i = 0; i < options.columns.length; i++) {
						if(options.columns[i].buttons) {

							options.columns[i].cellTemplate = (function(buttons) {
								return function(container, ei) {

									$.each(buttons, function(i, button) {
										var title = button.title,
											url = '#';

                                        if (button.auth && ! button.auth.call(this)) {
                                            return true;
                                        }

										if(button.url) {

											let id = encodeURIComponent(ei.data.id)
											url = Mustache.render(button.url, {id});
										}
										var el = $(Mustache.render('<a style="margin: 0 10px;" href="{{url}}">{{title}}</a>', {
											title: title,
											url: url
										}));

										if (button.onClick) {
											el.click(function() {

												button.onClick(ei.data, ei.component);
												return false;
											});
										}

										el.appendTo(container);



								if(button.del){

						$("<span style='margin:0 5px;vertical-align:1px'>|</span>").appendTo(container)

										 $("<a>").text("删除").click(function(){

								     DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function(sele){

							                if(sele){
                                           var  getId= ei.data.id
                               
 								           $.ajax({type:"delete",
 						                   url:$.config('apiUrl')+"restful/"+getId+"?_model="+button.del
								                 }).then(function(a){

								                if(a.status="success"){

								                    DevExpress.ui.notify({
								                      message: function() {

								                       gridComponent = $("#content .crud-grid").dxDataGrid('instance');

								                     gridComponent.option('dataSource').load();

								                       return "成功删除";
								                                     }
								                                   },"success", 1000)

								                               }else{

								                    DevExpress.ui.notify({

								                      message: function() {

								                       return "操作失败";
								                                     }
								                                   },"warning", 1000)
								                         }
								                      })
								                    }
								                })
								        }).appendTo(container)

										}

									});
								};
							})(options.columns[i].buttons);
						}
					}
					param['columns'] = options.columns;
				}

				if(options.onRenderGrid) {
					options.onRenderGrid.call(eventContext, $("#content .crud-grid"), $.extend({}, param, options.grid));
				} else {
					$("#content .crud-grid")[gridType]($.extend({}, param, options.grid));
				};

				// var gridInst = $("#content .crud-grid")[gridType]("instance");

				if(!options.search['mobile']) $("#content [data-search=mobile]").closest(".input-group").hide();
				if(!options.search['name']) $("#content [data-search=name]").closest(".input-group").hide();
				if(!options.search['lookup']) $("#content [data-search=lookup]").closest(".lookup").hide();
				if(!options.search['mobile'] && !options.search['name']) {
					$("#content .grid-search").hide();
				}

				var now = new Date()
				$("#date").dxDateBox({
					type: "date",
					value: now,
					displayFormat: 'yyyy-MM-dd',
					dateSerializationFormat: "yyyy-MM-dd",
					editorOptions: {
						displayFormat: 'yyyy-MM-dd',
						dateSerializationFormat: 'yyyy-MM-dd'
					}
				})

				$("#content .grid-search").click(function() {
					var name = $("#content [data-search=name]").val(),
						mobile = $("#content [data-search=mobile]").val(),
						dateA = $("#content #date").dxDateBox('option', 'value');

					if(name) {
						ds.searchExpr(options.search['name']);
						$("#content [data-search=mobile]").val('');
					} else if(mobile) {
						ds.searchExpr(options.search['mobile']);
						$("#content [data-search=name]").val('');
					} else if(dateA) {
						ds.searchExpr(options.search['dateA']);
						$("#content #date").dxDateBox('option', 'value');
					}

					ds.searchOperation("contains");
					ds.searchValue(name || mobile || dateA);
					ds.reload();
				});

				// $("#modify_pwd", $(this)).dxDataGrid(param);
			});
			function initCrudForm($c, context) {
				var id = context.params.id,
					formOptions = {
						readOnly: false,
						showColonAfterLabel: true,
						showValidationSummary: false,
						colCount: 1,
						validationGroup: "crud",
						items: [],
						onFieldDataChanged: function(e) {
							// console.log("onFieldDataChanged");
							// console.log(e);
						}
					};

					

				if(id) {
					 options.form.beforeDataShow =options.form.beforeDataShow || function(data){return data};
					formOptions.onContentReady = function(e) {
						store.byKey(id).then(function(resp) {

							if (options.form.beforeDataUpdate) {
								options.form.beforeDataUpdate(form, {data: resp});
							}
							e.component.option('formData', options.form.beforeDataShow(resp));

							if(options.form.afterDataUpdate) {
								options.form.afterDataUpdate(form, {data: resp});
							}
						});
					}
				}

				var form = $("#form", $c).dxForm($.extend(formOptions, options.form)).dxForm('instance');

				$("#form-container #save", $c).click(function () {
					var result = form.validate();

					if (! result.isValid) {
						var $el = result.validators[0].element();

						var offset = $el.offset();

						$('html, body').animate({
						    scrollTop: offset.top - $("header.app-header").height() - 20
						});

					} else {
						$("#form-container", $c).submit();
					}

					return false;
				});

				$("#form-container", $c).on("submit", function(e) {
					var bs = true;
					if(options.form.beforeSubmit) {
						bs = options.form.beforeSubmit(form, id);
					}

					$.when(bs).then(function(result) {
						if(result) {
							options.form.beforeDataSubmit = options.form.beforeDataSubmit || function(data){return data}
							if(id) {
								store.update(id, options.form.beforeDataSubmit(form.option('formData'))).then(function(values, resp) {
									DevExpress.ui.notify({
										message: "已更新",
									}, "success", 1000);

                                    if (options.form.onSaved) {
                                        options.form.onSaved.call(context, values, resp);
                                    } else {
                                        context.redirect('#/' + route);
                                    }
								}).fail(function() {
									DevExpress.ui.notify({
										message: $.crudStoreResp.message
									}, "warning", 2000);
								});
							} else {
								store.insert(options.form.beforeDataSubmit(form.option('formData'))).then(function(values, resp) {
									if(resp.status == "error") {
										DevExpress.ui.dialog.alert(resp.msg, '提示');
										return false;
									} else {
										DevExpress.ui.notify({
											message: "已完成",
										}, "success", 1000);
										context.redirect('#/' + route);
										//		        						context.redirect('#/' + route + '/edit/' + resp.model.id);
									}
								}).fail(function(resp) {
									DevExpress.ui.notify({
										message: resp,
									}, "warning", 2000);
								});
							}
						}
					})

					return false;
				});

				$("#form-container .delete", $c).click(function() {
					DevExpress.ui.dialog.confirm("确认删除吗?", "请确认").done(function(dialogResult) {
						if(dialogResult) {

							store.remove(id).then(function(resp) {

								DevExpress.ui.notify({
									message: "已删除",
								}, "success", 1000);
								context.redirect("#/" + route);
							});
						}
					});

					return false;
				});

				$("#form-container #cancel").click(function() {
					context.redirect("#/" + route);
					return false;
				});

				var saveNext = false;
				$("#form-container #save").click(function() {
					saveNext = false;
					return false;
				});
				$("#form-container #save-next").click(function() {
					saveNext = true;
					return false;
				});
			}

			// create or edit
			//			console.log("add crud " + route + "/edit");

			app.get('#/' + route + "/edit", function() {
				var eventContext = this,
					capable = $.extend({
						saveNext: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '新建'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});

			//			console.log("add crud " + route + "/edit/:id");

			app.get('#/' + route + "/edit/:id", function() {
				var eventContext = this,
					capable = $.extend({
						delete: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '编辑'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});
		}

			
	},

	dxCall: function() {
		var comp = $(this).data('dxComponents');
		if(comp && comp.length) {
			var inst = $(this)[comp[0]]("instance");

			return inst[arguments[0]].apply(inst, arguments.slice(1));
		} else {
			return undefined;
		}
	}
});

var routes = [
	'dashboard',
	'member-relations/show/:id',
	'member-check/:id',
	'subject-investor/:action',
	'subject-investor/:action/:id',
	'subject-agent/:action',
	'subject-agent/:action/:id',
	'page_vipclass',
	'table_vipcert',
	'page_vipcontacts',
	'page_vipbonus',
	'tz_management',
	'xz_contract',
	'tz_edit',
	'qy_management',
	'qy_form',
	'qy_edit',
	'order_list',
	'shj_management',
	'to_examine',
	'play_money',
	'money_details',
	'already_money',
	'examine_refuse',
	'user_management',
	'qy_managements',
	'now_list',
	'pt_bonus',
	'modify_pwd',
	'newproduct/:id',
	'newproduct',
	'rightsConsumes',
	'rightsChanges',
	'vip_information/:id',
	'vip_authority/:id',
	'project-details/:id',
	'integral-details/:id',
	'project-edit/:id',
	'score-details/:id'
];

var API = function(name, param) {
	if(typeof(param) === 'object') {
		var u = new Url($.config('apiUrl') + name);

		for(var k in param) {
			u.query[k] = param[k];
		}

		return u.toString();
	} else {
		return $.config('apiUrl') + name + (param ? "/" + param : "");
	}
};


$(function() {
	// if(!localStorage.accessToken) {
	// 	window.location.href = 'login.html';
	// 	return;
	// } else {
	// 	$.ajax({
	// 		headers: {
	// 			Authorization: "bearer " + localStorage.accessToken
	// 		},
	// 		url: API('auth/me'),
	// 		type: 'get',
	// 		success: function(data) {
	// 			$(".app").show();

	// 			$(".admin-name").text(data.username);
	// 			$(".auth-" + data.type).show();
	// 		},
	// 		error: function(resp) {
	// 			window.location.href = 'login.html';

	// 		}
	// 	});
	// }



    let initApp = () => {
		// let login = document.cookie;
		// if(login.indexOf('login')==-1){
		// 	return window.location.href = 'login.html'
		// }
        var app = $.sammy('#content', function() {
            var app = this;
            $.each(App.routes, function(i, route) {
                var m = route.name.match(/[^\/]*/);
                app.get('#/' + route.name, function() {

                    var eventContext = this;

                    route.onLoad && route.onLoad.call(route, eventContext, $('#content'));

                    // $.get('template/' + m[0] + '.html', function(resp) {
                    //  $('#content').html(resp).dxInit();
                    //  $("#content").trigger("route.loaded", [eventContext])
                    // });
                });
            });

            // for(var i = 0; i < routes.length; i++) {
            //  (function(route) {
            //      var m = route.match(/[^\/]*/);
            //      app.get('#/' + route, function() {

            //          var eventContext = this;

            //          $.get('template/' + m[0] + '.html', function(resp) {
            //              $('#content').html(resp).dxInit();
            //              $("#content").trigger("route.loaded", [eventContext])
            //          });
            //      });
            //  })(routes[i]);
            // }

            $.each(App.pages, function(i, page) {
                $.crud($.extend({
                    app: app
                }, page));
            })

        });

        app.bind('changed', {}, function() {
            App.setEventContext(this);
        });
        app.run('#/good');
    }
    //登录模块
            $(".app").show();
            $(".auth-" + 'super').show();

            initApp();

    // $.get($.config('apiUrl') + 'user').then(function (resp) {
    //     console.log(resp);
    //     if (resp.user && resp.user.type === 'admin') {
    //         let type = (resp.user.yxsm ? "college" : "super");

    //         App.login(resp.user);
            
    //         $(".app").show();
    //         $(".auth-" + type).show();

    //         initApp();

    //     } else {
    //         window.location.href = 'login.html';
    //     }
    // }).fail(err => {
    //     window.location.href = 'login.html';
    // });

    DevExpress.viz.currentTheme("generic.light");

    $("body").dxInit();

});
